package com.xing.binbackend.pattern.adapter24.ecommerce;

import com.xing.binbackend.pattern.adapter24.ecommerce.model.PayParams;
import com.xing.binbackend.pattern.adapter24.ecommerce.model.PayRequest;
import com.xing.binbackend.pattern.adapter24.ecommerce.model.PayResponse;
import com.xing.binbackend.pattern.adapter24.ecommerce.model.PayResult;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

//  旧版支付适配器实现（适配器核心）
@Component
public class WechatAdapter implements IPayment {
    private final WechatPaySDK wechatPay; // 被适配对象

    public WechatAdapter(WechatPaySDK wechatPay) {
        this.wechatPay = wechatPay;
    }

    @Override
    public PayResult pay(PayRequest request) {
        // 参数转换适配
        PayParams params = convertParams(request);
        // 调用旧版接口
        PayResponse payResponse = wechatPay.doPay(params);
        // 结果转换适配
        return convertResult(payResponse);
    }

    private PayParams convertParams(PayRequest request) {
        PayParams params = new PayParams();
        params.setOutTradeNo(request.getOrderId());
        params.setTotalFee(request.getAmount().multiply(BigDecimal.valueOf(100)).intValue()); //
        // 金额单位转换
        params.setOpenId(request.getOpenId());
        return params;
    }

    private PayResult convertResult(PayResponse response) {
        PayResult payResult = new PayResult();
        payResult.setReturnMsg(response.getMessage());
        return payResult;
    }
}
